﻿using CodeCity.AutomationMachine.DomainModels;
using NRules.Fluent.Dsl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace CodeCity.AutomationMachine.Rules
{
    public class HumanRule : Rule
    {
        public override void Define()
        {
            IEnumerable<Human> humans = null;
            When()
                .Match(() => humans);

            Then()
                .Do(context => Change(humans));
        }

        private void Change(IEnumerable<Human> humans)
        {
            var envTemperature = SkyEnvironment.Instance.Temperature;
            foreach (var human in humans)
            {
                if (human.RemainLife <= 0)
                {
                    human.IsDeaded = true;
                    continue;
                }
                if (human.Temperature > envTemperature)
                {
                    human.Temperature -= 0.00016;
                }
                else if (human.Temperature < envTemperature)
                {
                    human.Temperature += 0.00016;
                }
                if (human.IsPatient)
                {
                    human.GrowSpeed += 0.1;
                    continue;
                }
                var isInNormalTemperature = human.Temperature >= Human.MinNormalTemperature && human.Temperature <= Human.MaxNormalTemperature;
                if (isInNormalTemperature)
                {
                    human.TemperatureOutOfNormalSeconds -= 1;
                    if (human.TemperatureOutOfNormalSeconds < 0)
                    {
                        human.TemperatureOutOfNormalSeconds = 0;
                    }
                }
                else
                {
                    human.TemperatureOutOfNormalSeconds += 1;
                }
                if (human.TemperatureOutOfNormalSeconds >= 3600)
                {
                    human.IsPatient = true;
                }
                human.RemainLife -= human.GrowSpeed / 3600 / 24;
            }
        }
    }
}
